# Create your views here.
import markdown
from django.shortcuts import get_object_or_404, render, HttpResponseRedirect
from markdown.extensions.toc import TocExtension, slugify

from login.models import *


def index(request, id):
    if request.method == "POST":
        name = request.session.get('name')
        text = request.POST['text']
        # try:
        user = User.objects.get(name=name)
        news = News.objects.get(id=id)
        text = Message.objects.create(user=user,
                                      news_id=news.id,
                                      message=text
                                      )

        # except Exception as e:
        #     print("留言", e)
        return HttpResponseRedirect('/user/news/' + str(id))


    else:
        try:
            news = News.objects.get(id=id)
            message = Message.objects.filter(is_active=True, news__id=id).order_by('-time')
            type = Type.objects.filter(is_active=True)
            href = Href.objects.filter(is_active=True)
            MyHref = MyHref1.objects.filter(is_active=True)
            admiration = Admiration.objects.filter(is_active=True)
        except Exception as e:
            print(e)

        """
        博文详情
        """
        blog = get_object_or_404(News, pk=id)
        blog.viewed()
        # Markdown渲染文章(含目录)，注意Markdown的 M 大小写
        md = markdown.Markdown(
            extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.fenced_code',
                'markdown.extensions.tables',
                TocExtension(slugify=slugify),
            ]
        )
        # md文章内容
        blog.content = md.convert(blog.content)
        # 获取对应文章的全部评论，倒序显示

        context = {
            "blog": blog,
            'toc': md.toc,
            "news": news,
            "type": type,
            "href": href,
            "myhref": MyHref,
            "admiration": admiration,
            "message": message,

        }
        return render(request, 'user/index.html', context)
